package com.ltcode.auth.interfaces.controller;

import com.ltcode.auth.application.service.CaptchaApplicationService;
import com.ltcode.auth.domain.model.Captcha;
import com.ltcode.common.base.web.domain.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 验证码控制器
 * 
 * @author ltcode
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/captcha")
@RequiredArgsConstructor
public class CaptchaController {

    private final CaptchaApplicationService captchaApplicationService;

    @GetMapping("/char")
    public ApiResponse<Captcha.CaptchaResult> getCharCaptcha() {
        try {
            Captcha.CaptchaResult result = captchaApplicationService.generateCharCaptcha();
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("获取字符验证码失败", e);
            return ApiResponse.fail("获取验证码失败");
        }
    }

    @GetMapping("/math")
    public ApiResponse<Captcha.CaptchaResult> getMathCaptcha() {
        try {
            Captcha.CaptchaResult result = captchaApplicationService.generateMathCaptcha();
            return ApiResponse.ok(result);
        } catch (Exception e) {
            log.error("获取数学运算验证码失败", e);
            return ApiResponse.fail("获取验证码失败");
        }
    }

    @PostMapping("/validate")
    public ApiResponse<Void> validateCaptcha(@RequestParam String code, @RequestParam String uuid) {
        try {
            captchaApplicationService.validateCaptcha(code, uuid);
            return ApiResponse.ok();
        } catch (Exception e) {
            log.warn("验证码验证失败: uuid={}, code={}, error={}", uuid, code, e.getMessage());
            return ApiResponse.fail(e.getMessage());
        }
    }

    @GetMapping("/exists/{uuid}")
    public ApiResponse<Boolean> existsCaptcha(@PathVariable String uuid) {
        try {
            boolean exists = captchaApplicationService.existsCaptcha(uuid);
            return ApiResponse.ok(exists);
        } catch (Exception e) {
            log.error("检查验证码是否存在失败: uuid={}", uuid, e);
            return ApiResponse.fail("检查验证码失败");
        }
    }

    @DeleteMapping("/{uuid}")
    public ApiResponse<Void> deleteCaptcha(@PathVariable String uuid) {
        try {
            captchaApplicationService.deleteCaptcha(uuid);
            return ApiResponse.ok();
        } catch (Exception e) {
            log.error("删除验证码失败: uuid={}", uuid, e);
            return ApiResponse.fail("删除验证码失败");
        }
    }
}
